import { defineStore } from 'pinia'
import { ref } from 'vue'
import { request } from '../utils/request'

interface Product {
  id: number
  name_en: string
  name_es: string
  name_ja: string
  description_en: string
  description_es: string
  description_ja: string
  category: string
  images: string[]
  specifications_en: string
  specifications_es: string
  specifications_ja: string
  certifications: string[]
  order: number
  isActive: boolean
}

interface Category {
  id: string
  name_en: string
  name_es: string
  name_ja: string
  order: number
}

interface ProductSettings {
  products_page_title_en?: string
  products_page_title_es?: string
  products_page_title_ja?: string
  products_page_subtitle_en?: string
  products_page_subtitle_es?: string
  products_page_subtitle_ja?: string
  products_page_description_en?: string
  products_page_description_es?: string
  products_page_description_ja?: string
  products_header_image?: string
  products_list?: Product[]
  products_categories?: Category[]
  products_detail_layout?: {
    showSpecifications: boolean
    showCertifications: boolean
    showNutrition: boolean
    imageCarouselEnabled: boolean
    relatedProductsCount: number
  }
  [key: string]: any
}

export const useProductsStore = defineStore('products', () => {
  const settings = ref<ProductSettings>({})
  const loading = ref(false)
  const error = ref<string | null>(null)
  
  // 获取产品页面配置
  const fetchSettings = async () => {
    loading.value = true
    error.value = null
    
    try {
      const response = await request.get('/settings/public') as any
      if (response && response.data) {
        settings.value = response.data || {}
        console.log('用户端获取到的产品配置数据:', response.data)
      } else {
        error.value = response?.message || '获取配置失败'
      }
    } catch (err: any) {
      error.value = err.message || '网络错误'
      console.error('获取产品配置失败:', err)
    } finally {
      loading.value = false
    }
  }
  
  // 获取多语言字段的通用方法
  const getMultiLangField = (obj: any, fieldPrefix: string, lang: string, fallback?: string): string => {
    const fieldKey = `${fieldPrefix}_${lang}`
    return obj[fieldKey] || fallback || ''
  }
  
  // 根据语言获取页面标题
  const getPageTitle = (lang: string) => {
    return getMultiLangField(settings.value, 'products_page_title', lang, 'Our Products')
  }
  
  // 根据语言获取页面副标题
  const getPageSubtitle = (lang: string) => {
    return getMultiLangField(settings.value, 'products_page_subtitle', lang)
  }
  
  // 根据语言获取页面描述
  const getPageDescription = (lang: string) => {
    return getMultiLangField(settings.value, 'products_page_description', lang)
  }
  
  // 获取页面头部背景图
  const getHeaderImage = () => {
    return settings.value.products_header_image || ''
  }
  
  // 获取产品列表
  const getProductList = (): Product[] => {
    return settings.value.products_list || []
  }
  
  // 获取活跃产品列表
  const getActiveProducts = (): Product[] => {
    return getProductList().filter(product => product.isActive)
  }
  
  // 根据分类获取产品
  const getProductsByCategory = (categoryId: string): Product[] => {
    return getActiveProducts().filter(product => product.category === categoryId)
  }
  
  // 根据ID获取单个产品
  const getProductById = (id: number): Product | null => {
    return getProductList().find(product => product.id === id) || null
  }
  
  // 获取产品分类列表
  const getCategories = (): Category[] => {
    return settings.value.products_categories || []
  }
  
  // 根据语言获取产品名称
  const getProductName = (product: Product, lang: string): string => {
    return getMultiLangField(product, 'name', lang, product.name_en)
  }
  
  // 根据语言获取产品描述
  const getProductDescription = (product: Product, lang: string): string => {
    return getMultiLangField(product, 'description', lang, product.description_en)
  }
  
  // 根据语言获取产品规格
  const getProductSpecifications = (product: Product, lang: string): string => {
    return getMultiLangField(product, 'specifications', lang, product.specifications_en)
  }
  
  // 根据语言获取分类名称
  const getCategoryName = (category: Category, lang: string): string => {
    return getMultiLangField(category, 'name', lang, category.name_en)
  }
  
  // 根据分类ID获取分类名称
  const getCategoryNameById = (categoryId: string, lang: string): string => {
    const category = getCategories().find(cat => cat.id === categoryId)
    return category ? getCategoryName(category, lang) : categoryId
  }
  
  // 获取产品的主图
  const getProductMainImage = (product: Product): string => {
    return product.images && product.images.length > 0 ? product.images[0] : ''
  }
  
  // 获取相关产品
  const getRelatedProducts = (currentProduct: Product, count: number = 3): Product[] => {
    const detailLayout = settings.value.products_detail_layout
    const maxCount = detailLayout?.relatedProductsCount || count
    
    return getActiveProducts()
      .filter(product => 
        product.id !== currentProduct.id && 
        product.category === currentProduct.category
      )
      .slice(0, maxCount)
  }
  
  // 获取详情页布局配置
  const getDetailLayout = () => {
    return settings.value.products_detail_layout || {
      showSpecifications: true,
      showCertifications: true,
      showNutrition: false,
      imageCarouselEnabled: true,
      relatedProductsCount: 3
    }
  }
  
  // 搜索产品
  const searchProducts = (keyword: string, lang: string): Product[] => {
    if (!keyword.trim()) return getActiveProducts()
    
    const lowerKeyword = keyword.toLowerCase()
    return getActiveProducts().filter(product => {
      const name = getProductName(product, lang).toLowerCase()
      const description = getProductDescription(product, lang).toLowerCase()
      const categoryName = getCategoryNameById(product.category, lang).toLowerCase()
      
      return name.includes(lowerKeyword) || 
             description.includes(lowerKeyword) || 
             categoryName.includes(lowerKeyword) ||
             product.certifications.some(cert => cert.toLowerCase().includes(lowerKeyword))
    })
  }
  
  return {
    settings,
    loading,
    error,
    fetchSettings,
    getPageTitle,
    getPageSubtitle,
    getPageDescription,
    getHeaderImage,
    getProductList,
    getActiveProducts,
    getProductsByCategory,
    getProductById,
    getCategories,
    getProductName,
    getProductDescription,
    getProductSpecifications,
    getCategoryName,
    getCategoryNameById,
    getProductMainImage,
    getRelatedProducts,
    getDetailLayout,
    searchProducts
  }
})